package com.angel.activity;


import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.angel.entity.ActivityBeanList;
import com.angel.entity.Task;
import com.angel.port.IActivity;
import com.angel.service.TaskService;
import com.angel.util.BaseUtil;
import com.angel.util.StringUtil;
import com.angel.util.UserInfoUtil;
import com.google.gson.reflect.TypeToken;
import com.umeng.analytics.MobclickAgent;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Register2Activity extends Activity implements IActivity{
	/**
	 */
	private Button back_btn;
	private Button next_btn;
	private EditText password1,password2,indentifyCode;
	private HashMap<String,String> map=new HashMap<String,String>();
	private String phoneNum,identifyCode;
	private Intent intent;
    private  ActivityBeanList activityBeanList;
    private String isBind;
    private Context context;
    private AlertDialog dialog;//显示成功注册的对话框
    private ProgressDialog progressDialog;
    private Button closeDialogBtn;//关闭对话框的按钮
    private TextView titleTxt;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register2);
		 MobclickAgent.onError(this);//自动捕获异常退出（FC ）
		context=Register2Activity.this;
		progressDialog=new ProgressDialog(context);
		progressDialog.setMessage("请稍后...");
		
		Intent tent=getIntent();
		phoneNum=tent.getStringExtra("telNum");
		identifyCode=tent.getStringExtra("identifyCode");
		isBind=tent.getStringExtra("isBind");
		
		back_btn = (Button)findViewById(R.id.register2_back_btn);
		next_btn = (Button)findViewById(R.id.register2_next_btn);
		password1=(EditText)findViewById(R.id.register_setpassword_02);
		password2=(EditText)findViewById(R.id.register_setpassword_12);
		indentifyCode=(EditText)findViewById(R.id.register_identityCody_02);
		titleTxt=(TextView)findViewById(R.id.register2_title_txt);
		
		back_btn.setOnClickListener( new ButtonActionListener());
		next_btn.setOnClickListener( new ButtonActionListener());
		
		/*动态设置标题*/
		if(isBind.equals("0")){
			titleTxt.setText(getResources().getText(R.string.CreateAccount));
		}else if(isBind.equals("1")){
			titleTxt.setText(getResources().getText(R.string.bindPnoneNum));
		}else if(isBind.equals("2")){
			titleTxt.setText(getResources().getText(R.string.findPassword));
	    }
	}
	private class ButtonActionListener implements OnClickListener {
		public void onClick(View v) {
			if (v.getId() == R.id.register2_back_btn) {
				finish();
			}
			if(v.getId() == R.id.register2_next_btn){
				String psw1=password1.getText().toString();
				String psw2=password2.getText().toString();
				String dentifycode=indentifyCode.getText().toString();
				
				boolean b1=checkLengh(psw1);
				boolean b2=checkPswAndIdentifyCode(psw1,psw2,dentifycode);
				if(b1&&b2){//若检查的密码和验证码符合要求
					map.put("telNum",phoneNum);
					map.put("password", psw1);
					map.put("isBind",isBind);
					map.put("userId", UserInfoUtil.getValue(context, "userId", "0"));
					//启动任务请求
					BaseUtil.startService(Task.REGISTER, Register2Activity.this, map);
					progressDialog.show();
				}
			}
			if(v.getId()==R.id.close_btn){
				dialog.dismiss();//点击按钮，关闭对话框
			}
		}
	}
	/*显示注册成功的对话框*/
	public void showSuccessRegister(){
//		AlertDialog.Builder builder=new AlertDialog.Builder(context);
//		LayoutInflater inflater=getLayoutInflater();
//		View view=inflater.inflate(R.layout.dialog_show, null);
//		closeDialogBtn=(Button)findViewById(R.id.close_btn);
//		closeDialogBtn.setOnClickListener(new ButtonActionListener());
//		builder.setView(view);
//		dialog=builder.create();
//		dialog.show();
		Dialog dialog1 = new Dialog(Register2Activity.this, R.style.MyDialog);
		dialog1.setContentView(R.layout.dialog_show);
		dialog1.show();
	}
	/*检查密码长度是否至少六位*/
	public boolean checkLengh(String psw1){
	//	int length=psw1.length();
			  String format="[a-z0-9]{6,}";
			  if(psw1.matches(format)){
				  return true;
			  }else{
					BaseUtil.makeToast(this, "请输入至少六位的密码");
				  return false;
			  }
	}
	/*检查输入密码和验证码*/
	public boolean checkPswAndIdentifyCode(String psw1,String psw2,String dentifycode){
		if(dentifycode.equals(identifyCode)){//判断验证码是否一致
			if(!StringUtil.isBlank(psw1)){
				if(!psw1.equals(psw2)){
					BaseUtil.makeToast(this, "您前后输入的密码不一致");
					return false;
				}
			}else{
				BaseUtil.makeToast(this, "请输入密码或者不能含空字符");
				return false;
			}
		}else{
			BaseUtil.makeToast(this, "您输入的验证码出错，请重新输入");
			return false;
		}
		return true;
	}
	@Override
	public void init() {
	}
	@Override
	public void refresh(Object... params) {
		 String isSucess="";
		 JSONObject jsonObject=null;
		 try {
			 jsonObject=new JSONObject((String)params[0]);
			 isSucess=jsonObject.getString("isSuccess");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		 if(isBind.equals("0")){//如果是注册
			 Type type=new TypeToken<ActivityBeanList>(){}.getType();
			 activityBeanList=(ActivityBeanList)BaseUtil.getEntityFromJson((String)params[0],type);
			 if(isSucess.equals("0")){//如果登录不成功
				 BaseUtil.makeToast(Register2Activity.this, "对不起，您的账号已存在，请重新输入");
			 }else{//如果登录成功，则将数据传递到下个Activity
				    intent = new Intent();
				    intent.setClass(Register2Activity.this, BottomMeunTab.class);
					intent.putExtra("jsonData",(String)params[0] );
					/*保存用户基本信息*/
					map=new HashMap<String,String>();
					map.put("phoneAccount", activityBeanList.getTelNum());
					map.put("password", password1.getText().toString());
					map.put("email", activityBeanList.getEmail());
					map.put("openid", activityBeanList.getWeibo());
					map.put("uid", activityBeanList.getQq());
					map.put("userId",activityBeanList.getUserId());
					map.put("userName",activityBeanList.getUserName());
					UserInfoUtil.setValue(context, map);
					
				    new Handler().postDelayed(new Runnable(){
						@Override
						public void run() {
							 startActivity(intent);	
							 finish();
							 TaskService.removeActivity(Register2Activity.this);
						}
				    }, 5000);
				    showSuccessRegister();
			 }
		 }else if(isBind.equals("1")){//若为绑定账号
			 if(isSucess.equals("0")){//如果绑定失败
				 BaseUtil.makeToast(Register2Activity.this, "对不起，网络出错，请稍后再试");
			 }else{//成功绑定
				 map.put("phoneAccount", phoneNum);
			 	 map.put("password", password1.getText().toString());
				 UserInfoUtil.setValue(context, map);
				 finish();
			 }
		 }else if(isBind.equals("2")){//找回密码操作
			 if(isSucess.equals("0")){//如果绑定失败
				 BaseUtil.makeToast(Register2Activity.this, "对不起，网络出错，请稍后再试");
			 }else{//成功绑定
				 BaseUtil.makeToast(Register2Activity.this, "您已重新设置密码");
			 }
		 }
		  progressDialog.dismiss();
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		 MobclickAgent.onResume(this);
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		 MobclickAgent.onPause(this);
	}
}
